package com.gzsxy.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 手写jwt
 * @date 2021/11/6 10:29
 */
public class JWTDemo {

    public static void main(String[] args) throws UnsupportedEncodingException {

        //头部 header
        JSONObject header = new JSONObject();
        header.put("Alg","HS256");

        //payLoad
        JSONObject payLoad = new JSONObject();
        payLoad.put("userName","mayikt644");
        payLoad.put("userAge","21");
        payLoad.put("userId","18888");
        //base64 对实现编码数据
        String jwtHeader = Base64.getEncoder().encodeToString(header.toJSONString().getBytes());
        String jwtpayLoad = Base64.getEncoder().encodeToString(payLoad.toJSONString().getBytes());

        String sigingkey = "mayiktkey";

        String sign = DigestUtils.md5DigestAsHex((payLoad.toJSONString()+sigingkey).getBytes());
        String jwt = jwtHeader+'.'+jwtpayLoad+'.'+sign;

        System.out.println(jwt);


        //验证jwt是否被修改，底层原理
        String payLoadStr =new String(Base64.getDecoder().decode(jwt.split("\\.")[1]),"utf-8");
        String jwtSign = jwt.split("\\.")[2];
        System.out.println(DigestUtils.md5DigestAsHex((payLoadStr+sigingkey).getBytes()).equals(jwtSign));

    }
}
